package com.lizk.rocketmq.transtion;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.LocalTransactionExecuter;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.TransactionCheckListener;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

import com.lizk.rocketmq.Config;

public class ProducerTransaction {
	public static void main(String[] args) {
		TransactionMQProducer producer = new TransactionMQProducer("PRODUCER_GROUP_TRANSACTION");
		try {
			producer.setNamesrvAddr(Config.NAMESRV_ADDR);
			 // 事务回查最小并发数
	        producer.setCheckThreadPoolMinSize(2);
	        // 事务回查最大并发数
	        producer.setCheckThreadPoolMaxSize(2);
	        // 队列数
	        producer.setCheckRequestHoldMax(2000);
	        
	        producer.setTransactionCheckListener(new TransactionCheckListener(){
				@Override
				public LocalTransactionState checkLocalTransactionState(MessageExt paramMessageExt) {
					System.out.println("定时检查消息状态");
					return LocalTransactionState.COMMIT_MESSAGE;
				}

	        });
			producer.start();
			Message msg = new Message("topic_transaction","transaction",UUID.randomUUID().toString(),"我是消息的内容".getBytes(Config.ENCODE_UTF8));
			SendResult sendResult = producer.sendMessageInTransaction(msg, new LocalTransactionExecuter(){
				@Override
				public LocalTransactionState executeLocalTransactionBranch(Message paramMessage, Object paramObject) {
					System.out.println("处理本地业务");
					return LocalTransactionState.COMMIT_MESSAGE;
				}
			}, null);
			System.out.println(sendResult);
		} catch (MQClientException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		
	}
}
